package com.xiaozhengkeji.colastartboot.api;


import cn.dev33.satoken.annotation.SaCheckLogin;

import cn.hutool.system.oshi.OshiUtil;

import com.xiaozhengkeji.colastartboot.bean.ResponseBean;
import com.xiaozhengkeji.colastartboot.bean.type.ResCodeType;
import com.xiaozhengkeji.colastartboot.services.AppInfoService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.util.StringUtils;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;


/**
 * 系统Api
 */
@Slf4j
@RestController
@RequestMapping("/web/system")
public class SystemApi {
    AppInfoService appInfoService;

    @Autowired
    public SystemApi(AppInfoService appInfoService) {
        this.appInfoService = appInfoService;
    }

    private static final DecimalFormat LOAD_FORMAT = new DecimalFormat("#.00");

    /**
     * 获取系统Info
     */
    @ApiOperation("获取系统Info")
    @GetMapping("/coreInfo")
    @SaCheckLogin
    public ResponseBean coreInfo() {

        HashMap<String, Object> coreInfo = new LinkedHashMap<>();
        long MaxMemory = Math.round(OshiUtil.getMemory().getTotal() / 1024.00 / 1024);
        //后端版本号
        coreInfo.put("BackendVersion", appInfoService.getVersion());
        //Cpu占用率
        coreInfo.put("CpuOccupancy", LOAD_FORMAT.format(100.0D - OshiUtil.getCpuInfo().getFree()));
        //内存总容量
        coreInfo.put("MaxMemory", MaxMemory);
        //内存可用
        coreInfo.put("UseMemory", MaxMemory - Math.round(OshiUtil.getMemory().getAvailable() / 1024.00 / 1024));
        //Cpu型号
        coreInfo.put("CpuModel", StringUtils.substringBefore(OshiUtil.getCpuInfo().getCpuModel(), "\n"));
        //操作系统
        coreInfo.put("OSSystem", OshiUtil.getOs().getFamily()
                + " " + OshiUtil.getOs().getVersionInfo().getVersion()
                + " " + OshiUtil.getOs().getVersionInfo().getBuildNumber());
        return new ResponseBean(ResCodeType.Success, new Date().toString(), coreInfo, null);
    }
}
